import React, { useState, useCallback } from 'react';
import { DatePicker, Button, Input, message } from 'antd';
import {
  BoldOutlined, ItalicOutlined, UnderlineOutlined, StrikethroughOutlined,
  LinkOutlined, PictureOutlined,
  OrderedListOutlined, UnorderedListOutlined,
  AlignLeftOutlined, AlignCenterOutlined, AlignRightOutlined,
  UndoOutlined, RedoOutlined, PlusOutlined, MinusCircleOutlined
} from '@ant-design/icons';
import { useEditor, EditorContent } from '@tiptap/react';
import StarterKit from '@tiptap/starter-kit';
import Underline from '@tiptap/extension-underline';
import TextAlign from '@tiptap/extension-text-align';
import TextStyle from '@tiptap/extension-text-style';
import { Color } from '@tiptap/extension-color';
import Link from '@tiptap/extension-link';
import Image from '@tiptap/extension-image';
import style from './TPD.module.css';

const TiptapToolbar = ({ editor }) => {
  const setLink = useCallback(() => {
    const previousUrl = editor.getAttributes('link').href;
    const url = window.prompt('URL', previousUrl);
    if (url === null) return;
    if (url === '') {
      editor.chain().focus().extendMarkRange('link').unsetLink().run();
      return;
    }
    editor.chain().focus().extendMarkRange('link').setLink({ href: url }).run();
  }, [editor]);

  const addImage = useCallback(() => {
    const url = window.prompt('URL');
    if (url) {
      editor.chain().focus().setImage({ src: url }).run();
    }
  }, [editor]);

  if (!editor) return null;

  return (
    <div className={style['tpd-tiptap-toolbar']}>
      <div className={style['toolbar-group']}>
        <button onClick={() => editor.chain().focus().undo().run()} disabled={!editor.can().undo()}><UndoOutlined /></button>
        <button onClick={() => editor.chain().focus().redo().run()} disabled={!editor.can().redo()}><RedoOutlined /></button>
      </div>
      <div className={style['toolbar-group']}>
        <button onClick={() => editor.chain().focus().toggleBold().run()} className={editor.isActive('bold') ? style['is-active'] : ''}><BoldOutlined /></button>
        <button onClick={() => editor.chain().focus().toggleItalic().run()} className={editor.isActive('italic') ? style['is-active'] : ''}><ItalicOutlined /></button>
        <button onClick={() => editor.chain().focus().toggleUnderline().run()} className={editor.isActive('underline') ? style['is-active'] : ''}><UnderlineOutlined /></button>
        <button onClick={() => editor.chain().focus().toggleStrike().run()} className={editor.isActive('strike') ? style['is-active'] : ''}><StrikethroughOutlined /></button>
      </div>
      <div className={style['toolbar-group']}>
        <input type="color" onInput={event => editor.chain().focus().setColor(event.target.value).run()} value={editor.getAttributes('textStyle').color || '#000000'} className={style['toolbar-color-input']} />
      </div>
      <div className={style['toolbar-group']}>
        <button onClick={() => editor.chain().focus().setTextAlign('left').run()} className={editor.isActive({ textAlign: 'left' }) ? style['is-active'] : ''}><AlignLeftOutlined /></button>
        <button onClick={() => editor.chain().focus().setTextAlign('center').run()} className={editor.isActive({ textAlign: 'center' }) ? style['is-active'] : ''}><AlignCenterOutlined /></button>
        <button onClick={() => editor.chain().focus().setTextAlign('right').run()} className={editor.isActive({ textAlign: 'right' }) ? style['is-active'] : ''}><AlignRightOutlined /></button>
      </div>
      <div className={style['toolbar-group']}>
        <button onClick={() => editor.chain().focus().toggleBulletList().run()} className={editor.isActive('bulletList') ? style['is-active'] : ''}><UnorderedListOutlined /></button>
        <button onClick={() => editor.chain().focus().toggleOrderedList().run()} className={editor.isActive('orderedList') ? style['is-active'] : ''}><OrderedListOutlined /></button>
      </div>
      <div className={style['toolbar-group']}>
        <button onClick={setLink} className={editor.isActive('link') ? style['is-active'] : ''}><LinkOutlined /></button>
        <button onClick={addImage}><PictureOutlined /></button>
      </div>
    </div>
  );
};

const ThirdPartyData = () => {
  const [projectNo] = useState('P123123231231');
  const [projectName] = useState('CRM系统');
  const [services, setServices] = useState([
    { name: '', date: '' },
    { name: '', date: '' },
  ]);
  const [info, setInfo] = useState('');
  const editor = useEditor({
    extensions: [
      StarterKit, Underline,
      TextAlign.configure({ types: ['heading', 'paragraph'] }),
      TextStyle, Color,
      Link.configure({ openOnClick: false }),
      Image,
    ],
    content: info,
    onUpdate: ({ editor }) => {
      setInfo(editor.getHTML());
    },
  });

  const handleServiceChange = (idx, key, value) => {
    const newServices = [...services];
    newServices[idx][key] = value;
    setServices(newServices);
  };
  const handleServiceDateChange = (idx, date) => {
    const newServices = [...services];
    newServices[idx].date = date ? date.format('YYYY-MM-DD') : '';
    setServices(newServices);
  };
  const addService = () => {
    setServices([...services, { name: '', date: '' }]);
  };
  const removeService = idx => {
    if (services.length > 1) {
      setServices(services.filter((_, i) => i !== idx));
    }
  };

  const handleSave = () => {
    console.log({ projectNo, projectName, services, info });
    message.success('保存成功！');
  };

  const handleCancel = () => {
    message.info('已取消');
  };

  return (
    <div className={style['tpd-modal']} style={{maxWidth: 800, margin: '40px auto', background: '#f5f7fa', borderRadius: 6, boxShadow: '0 2px 12px #0001', paddingBottom: 24}}>
      <div className={style['tpd-header']}>第三方资料</div>
      <div className={style['tpd-info-row']}>
        <span>项目编号{projectNo}</span>
        <span>项目名称：{projectName}</span>
      </div>
      <div className={style['tpd-label']}>第三方服务到期时间：</div>
      {services.map((item, idx) => (
        <div className={style['tpd-service-row']} key={idx}>
          <Input
            className={style['tpd-service-input']}
            placeholder="输入服务名称"
            value={item.name}
            onChange={e => handleServiceChange(idx, 'name', e.target.value)}
          />
          <DatePicker
            className={style['tpd-service-date']}
            value={item.date ? (window.dayjs ? window.dayjs(item.date, 'YYYY-MM-DD') : undefined) : null}
            onChange={date => handleServiceDateChange(idx, date)}
            placeholder="选择到期时间"
            format="YYYY-MM-DD"
          />
          <Button icon={<PlusOutlined />} className={style['tpd-service-btn']} onClick={addService} type="text" />
          {services.length > 1 && (
            <Button icon={<MinusCircleOutlined />} className={style['tpd-service-btn']} onClick={() => removeService(idx)} type="text" />
          )}
        </div>
      ))}
      <div className={style['tpd-label']} style={{marginTop:16}}>第三方信息资料：</div>
      <div className={style['tpd-editor-wrap']}>
        <TiptapToolbar editor={editor} />
        <EditorContent editor={editor} className={style['tpd-editor-content']} />
      </div>
      <div className={style['tpd-footer']}>
        <Button type="primary" className={style['tpd-btn']} onClick={handleSave}>保存</Button>
        <Button className={style['tpd-btn']} onClick={handleCancel}>取消</Button>
      </div>
    </div>
  );
};

export default ThirdPartyData;
